package cn.conac.rc.auth.service;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cn.conac.rc.auth.entity.RoleEntity;
import cn.conac.rc.auth.repository.RoleRepository;
import cn.conac.rc.auth.vo.RoleVo;
import cn.conac.rc.framework.jpa.Criteria;
import cn.conac.rc.framework.jpa.Restrictions;
import cn.conac.rc.framework.service.GenericService;

@Service
public class RoleService extends GenericService<RoleEntity, Integer> {
	@Autowired
	private RoleRepository roleRepository;

	/**
	 * 查询角色列表
	 * @param role
	 * @return
	 * @throws Exception
	 */
	public Page<RoleEntity> list(RoleVo role) throws Exception {
        try {
            Pageable pageable = new PageRequest(role.getPage(), role.getSize());
            Criteria<RoleEntity> dc = this.createCriteria(role);
            return roleRepository.findAll(dc, pageable);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
	
	/**
	 * 查询角色列表拼装条件
	 * @param role
	 * @return
	 */
	private Criteria<RoleEntity> createCriteria(RoleEntity role) {
		Criteria<RoleEntity> dc = new Criteria<RoleEntity>();
		if (StringUtils.isNotBlank(role.getRoleName())) {
			dc.add(Restrictions.like("roleName", role.getRoleName(), true));
		}
		return dc;
	}
	
	
	/**
	 * 通过用户id查询角色
	 * @param userId
	 */
	public List<RoleEntity> findRolesByUserId(String userId){
		return roleRepository.findRolesByUserId(userId);
	}
}

